/**
 * 合约管理
 * @Author: Damen
 * @Data: Created in 2018/3/18
 */
var urlParams = {
    searchAction: webRoot + "/contract/user/findContractPage",
    insertAction: webRoot + "/purchaseSale/user/insertPurchaseSale",
    buyAction: webRoot + "/purchaseSale/user/tradeContract",
    buyContract: webRoot + "/contract/user/buyContract",
    selectAction: webRoot + "/user/selectUser",
    logoutAction: webRoot + "/login/logout"
};
var curTabId = 0, curDialogTabId = 11;       //0:收购合约;1:出售合约
var maxNum = 0, price = 0;
var dialogTab, quantity, num, contractDatas, selectContract;
$(function () {
    Bui.tab({
        srcNode: '#tab',
        elCls: 'nav-tabs',
        itemStatusCls: {
            'selected': 'active'
        },
        panelContainer: '#panel'//如果不指定容器的父元素，会自动生成
    });

    Bui.tab({
        srcNode: '#dialog_tab',
        elCls: 'nav-tabs',
        itemStatusCls: {
            'selected': 'active'
        },
        panelContainer: '#panel'//如果不指定容器的父元素，会自动生成
    });
    CommonClass.loadCommonCombo($('.purchaseContractId'), {
        sqlKey: 'com.mg.mapper.ContractMapper.selectPageInfo',
        paramMap: null
    }, "id", "contractName");
    CommonClass.loadCommonCombo($('.searchContractId'), {
        sqlKey: 'com.mg.mapper.ContractMapper.selectPageInfo',
        paramMap: null
    }, "id", "contractName", "All");
    CommonClass.loadCommonCombo($('.saleContractId'), {
        sqlKey: 'com.mg.mapper.PowerAccountMapper.selectPageInfo',
        paramMap: {userId: session.userInfo.id}
    }, "contractId", "contractName", null, function (data) {
        contractDatas = data;
    });
    initGrid();
    initForm();
    initEvent();
    initContractList()

});

function initContractList() {
    if (reqContractId) {
        if (contractDtoList.length > 0) {
            var index = -1;
            for (var i in contractDtoList) {
                if (contractDtoList[i].id + "" == reqContractId) {
                    index = i;
                    selectContract = contractDtoList[i]
                }
            }
            if (index < 0) {
                return;
            }
            $("span[name=contractNameSpan]").removeClass("click");
            $($("span[name=contractNameSpan]")[index]).addClass("click");
            clickContract(reqContractId)
        }
    } else {
        if (contractDtoList.length > 0) {
            $("span[name=contractNameSpan]").removeClass("click");
            $($("span[name=contractNameSpan]")[0]).addClass("click");
            selectContract = contractDtoList[0]
            clickContract(contractDtoList[0].id)
        }


    }
}

function setNum(data) {
    if (data[0]) {
        var num1 = (data[0].computingPowerNum - data[0].frozenComputingPowerNum)
        if (num1) {
            num = parseInt(num1);
        } else {
            num = 0;
        }
    } else {
        num = 0;
    }
    $(".num").val(num);
}

function initGrid() {
    var columns = [
        {title: '合约名', dataIndex: 'contractName', width: '20%'},
        {title: '合约上线时间', dataIndex: 'onlineTime', width: '20%'},
        {title: '剩余数量', dataIndex: 'remainderNum', width: '20%'},
        {title: '单价', dataIndex: 'price', width: '20%'},
        {
            title: '操作', dataIndex: 'handle', elCls: 'center', width: '20%', renderer: function () {
            var value = '<span class="grid-command sale">点击出售</span>';
            if (curTabId == 1) {
                value = '<span class="grid-command purchase">点击购买</span>';
            }
            return value;
        }
        }
    ];
    store = Bui.store({
        url: urlParams.searchAction,
        // autoLoad: true,
        root: 'list',               //存放数据的字段名(rows)
        totalProperty: 'total',
        pageSize: 50	// 配置分页数目
    });
    grid = Bui.grid({
        render: '#fileListGrid',
        columns: columns,
        width: "100%",
        store: store,
        bbar: {
            // pagingBar:表明包含分页栏
            pagingBar: true
        }
    });
    var obj = {
        type: 0,
        state: "交易中",
        userId: session.userInfo.id
    };
    store.load(obj);
    grid.on('cellclick', function (ev) {
        var record = ev.record, //点击行的记录
            field = ev.field, //点击对应列的dataIndex
            target = $(ev.domTarget); //点击的元素
        if (target.hasClass('purchase')) {
            purchaseContract(record)
        }
        if (target.hasClass('sale')) {
            saleContract(record)
        }
    });
}

function purchaseContract(record) {
    $.ajax({
        type: 'post',
        url: webRoot + "purchaseSale/user/getPurchaseSale.do",
        cache: false,
        data: {id: record.id, state: "交易中",},
        dataType: 'json',
        success: function (data) {
            if (data && data.id) {
                document.getElementById("purchaseSaleRecordEditForm").reset();
                purchaseSaleRecordEditForm.setRecord(data);
                $(".spanContractName").html(data.contractName);
                price = data.price;
                maxNum = data.remainderNum;
                $(".spanPrice").html(data.price);
                $(".maxNum").html(data.remainderNum + "份");
                $(".contractNumDiv").hide();
                purchaseSaleRecordDialog.set("title", "收购合约");
                purchaseSaleRecordDialog.show();
            } else {
                BUI.Message.Alert("出售信息不在，请重新查询", 'error');
            }
        },
        error: function () {
            BUI.Message.Alert("系统错误", 'error');
        }
    });
}

function saleContract(record) {
    $.ajax({
        type: 'post',
        url: webRoot + "purchaseSale/user/getDetail.do",
        cache: false,
        data: {id: record.id, state: "交易中"},
        dataType: 'json',
        success: function (data) {
            if (data) {
                if (data.purchaseSale== null) {
                    BUI.Message.Alert("出售信息不在，请重新查询", 'error');
                    return
                }
                if (data.powerAccount== null) {
                    BUI.Message.Alert("没有该合约算力，选择其他合约", 'error');
                    return
                }
                document.getElementById("purchaseSaleRecordEditForm").reset();
                purchaseSaleRecordEditForm.setRecord(data.purchaseSale);
                $(".spanContractName").html(data.purchaseSale.contractName);
                price = data.purchaseSale.price;
                maxNum = data.purchaseSale.remainderNum;
                $(".spanPrice").html(data.purchaseSale.price);
                $(".maxNum").html(data.purchaseSale.remainderNum + "份");
                $(".contractNumDiv").show();
                var contractNum = data.powerAccount.computingPowerNum - data.powerAccount.frozenComputingPowerNum
                $(".contractNum").html(contractNum + "份");
                purchaseSaleRecordDialog.set("title", "出售合约");
                purchaseSaleRecordDialog.show();
            } else {
                BUI.Message.Alert("出售信息不在，请重新查询", 'error');
            }
        },
        error: function () {
            BUI.Message.Alert("系统错误", 'error');
        }
    });
}

/**
 * 添加监听
 */
function initEvent() {
    $("a[name=contractBtn]").on("click", function () {
        document.getElementById("saleInfoForm").reset();
        document.getElementById("purchaseInfoForm").reset();

        CommonClass.fieldVaild();
        setNum(contractDatas);
        dialog.show();
    });
    $("#buyBtn").on("click", function () {
        buyBtnClick();
        // $(".bar-warning").width("60%");
    });
    $("span[name=contractNameSpan]").on("click", function () {
        $("span[name=contractNameSpan]").removeClass("click");
        $(this).addClass("click");
        clickContract($(this).attr("contractId"));
        // $(".bar-warning").width("60%");
    });
    $(".purchasePrice").on("change", function () {
        purchasePriceChange($(".purchasePrice").val())
    });
    $(".computingPowerNum").on("change", function () {
        computingPowerNumChange($(".computingPowerNum").val())
    });
    $(".buynum").on("change", function () {
        buynumChange($(".buynum").val())
    });
    $(".purchaseContractId").on("change", function () {
        var price = $(".purchasePrice").val();
        if (price) {
            purchasePriceChange(price)
        }
    });
    $(".saleContractId").on("change", function (e, value) {
        var contractId = $(".saleContractId").val();
        changeSaleContractId(contractId)
    });
    var contractMgrSearchForm = Bui.formRender("contractMgrSearchForm");
    contractMgrSearchForm.on('beforesubmit', function (ev) {
        //序列化成对象
        var obj = contractMgrSearchForm.serializeToObject();
        obj.start = 0; //返回第一页
        obj.state = "交易中"
        if (curTabId == 0) {
            obj.type = 0

        } else {
            obj.type = 1
        }
        obj.userId = session.userInfo.id
        store.load(obj);
        return false;
    });
}

function buyBtnClick() {
    var value = $(".buynum").val();
    if (value == undefined || value == null || value == "") {
        BUI.Message.Alert('购买数量不能为空！', function () {
        }, 'warning');
        return;
    }
    if (value < 1) {
        BUI.Message.Alert('购买数量不能小于1', function () {
        }, 'warning');
        return;
    }
    if (value < selectContract.minimumNumber) {
        BUI.Message.Alert('购买数量不能小于最小购买份数', function () {
        }, 'warning');
        return;
    }
    if (!buynumChange(value)) {
        return;
    }
    $(".machine_type_name").html(selectContract.machineTypeName + "," + selectContract.remark)
    $(".graphics").html(selectContract.graphics);
    $(".graphics_num").html(selectContract.graphicsNum);
    $(".rated_power").html(selectContract.ratedPower);
    $(".computing_power").html(selectContract.computingPower1);
    $(".min_computing_power").html(selectContract.computingPower * selectContract.minimumNumber);
     if(selectContract.contractBook){
         $(".contractBook").empty();
         $(".contractBook").append(selectContract.contractBook)
     }

    contractBookDialog.show()

}

function buynumChange(value) {
    if (selectContract.id) {
        if (value > selectContract.stock) {
            BUI.Message.Alert('购买数量不能大于库存！', function () {
            }, 'warning');

            return false;
        }
        var money = value * selectContract.price;
        $(".buyMoney").html(money + "元")

        if (money > (user.balance - user.frozeMoney)) {
            BUI.Message.Alert('可用金额不足请充值！', function () {
            }, 'warning');
            return false;
        }
        return true;

    }

}

function clickContract(contractId) {
    $(".buyMoney").html("0.00元");
    $(".buynum").val("");
    for (var i in contractDtoList) {
        if (contractDtoList[i].id + "" == contractId) {
            selectContract = contractDtoList[i];
        }
    }
    if (selectContract.stock > 0) {
        $('#buyBtn').removeAttr("disabled");
        $("#buyBtn").html("购买");
        $("#buyBtn").removeClass("button-inverse");
        $("#buyBtn").addClass("button-warning");

    } else {
        $("#buyBtn").attr("disabled", "true");
        $("#buyBtn").html("已售罄");
        $("#buyBtn").removeClass("button-warning");
        $("#buyBtn").addClass("button-inverse");
    }
    var rate = (selectContract.total - selectContract.stock) / selectContract.total * 100
    rate = parseFloat(rate.toFixed(2));
    var contractHtml = " <div class=\"contract_t\">\n" +
        "                        <div>\n" +
        "                            <dt>售价（CNY）</dt>\n" +
        "                            <dd>￥" + selectContract.price + "</dd>\n" +
        "                        </div>\n" +
        "                        <div>\n" +
        "                            <dt>算力（Mb/s）</dt>\n" +
        "                            <dd>" + selectContract.computingPower + "</dd>\n" +
        "                        </div>\n" +
        "                        <div>\n" +
        "                            <dt>电费（元/天）</dt>\n" +
        "                            <dd style=\"color:#ff8a00;\">" + selectContract.electricityFee + "</dd>\n" +
        "                        </div>\n" +
        "                    </div>\n" +
        "                    <div class=\"contract_t2\">\n" +
        "                        <div>\n" +
        "                            <dt>管理费</dt>\n" +
        "                            <dd>" + selectContract.managementCost + "%</dd>\n" +
        "                        </div>\n" +
        "                        <div>\n" +
        "                            <dt>交割时间</dt>\n" +
        "                            <dd>" + selectContract.deliveryTime + " </dd>\n" +
        "                        </div>\n" +
        "                        <div>\n" +
        "                            <dt>库存</dt>\n" +
        "                            <dd><span name=\"stock\" style=\"font-size:16px;\">" + selectContract.stock + "</span>Mb/s</dd>\n" +
        "                        </div>\n" +
        "                        <div>\n" +
        "                            <dt>最小购买份数</dt>\n" +
        "                            <dd>" + selectContract.minimumNumber + "</dd>\n" +
        "                        </div>\n" +
        "                    </div>\n" +
        "                    <div class=\"progress-bar\">\n" +
        "                        <div class=\"progress progress-striped\">\n" +
        "                            <div class=\"bar bar-warning\" style=\"width: " + rate + "%;\"></div>\n" +
        "                        </div>\n" +
        "                    </div>\n" +
        "                    <div style=\"margin-top: 15px\">\n" +
        "                        <label class=\"text\">当前进度" + rate + "%</label>\n" +
        "                        <label class=\"text\" style=\"float: right\">剩余可售" + selectContract.stock + "</label>\n" +
        "                    </div>";
    var contractContent = "table cellpadding=\"0\" cellspacing=\"0\" width=\"100%\">\n" +
        "                    <tbody>\n" +
        "                    <tr>\n" +
        "                        <td width=\"12%\">合约类型</td>\n" +
        "                        <td width=\"38%\">\n" +
        "                            <span>" + selectContract.contractType + "</span>\n" +
        "                        </td>\n" +
        "                        <td width=\"12\">合约单位</td>\n" +
        "                        <td width=\"38%\"><span>" + selectContract.computingPower + "MB/s</span></td>\n" +
        "                    </tr>\n" +
        "                    <tr>\n" +
        "                        <td>收益发放时间</td>\n" +
        "                        <td>\n" +
        "                            <span>" + selectContract.incomePaymentTime + "</span>\n" +
        "                        </td>\n" +
        "                        <td>电费</td>\n" +
        "                        <td><span>" + selectContract.electricityFee + "元/天</span></td>\n" +
        "                    </tr>\n" +
        "                    <tr>\n" +
        "                        <td>管理费</td>\n" +
        "                        <td><span>" + selectContract.managementCost + "%</span></td>\n" +
        "                        <td>结算周期</td>\n" +
        "                        <td><span>" + selectContract.settlementCycle + "</span></td>\n" +
        "\n" +
        "                    </tr>\n" +
        "                    <tr>\n" +
        "                        <td width=\"12%\">合约周期</td>\n" +
        "                        <td width=\"88%\" colspan=\"3\"><span>" + selectContract.contractCycle + "</span></td>\n" +
        "                    </tr>\n" +
        "                    </tbody>\n" +
        "                </table>"

    $(".contract-content").empty();
    $(".contract-content").append(contractHtml);
    $(".contractContent").empty();
    $(".contractContent").append(contractContent);

    if (selectContract.riskHints) {
        $(".riskHints").empty()
        var riskHintstContent = ''
        var riskHints = selectContract.riskHints.split("\\n")
        for (var i = 0; i < riskHints.length; i++) {
            riskHintstContent += "<p>" + riskHints[i] + "</p>"
        }
        $(".riskHints").append(riskHintstContent)

    }


}

function computingPowerNumChange(value) {
    var total = price * value
    if (total) {
        if (value > maxNum) {
            $(".spanMoney").html("--元")
            $(".computingPowerNum").val(0)
            BUI.Message.Alert('合约数量不能大于最大数量！', function () {
            }, 'warning');

        } else {
            $(".spanMoney").html(total + "元")
        }
    } else {
        $(".spanMoney").html("--元")
    }
}

function changeSaleContractId(contractId) {
    $.ajax({
        type: 'post',
        url: webRoot + "/base/baseAction.do",
        cache: false,
        data: {
            sqlKey: 'com.mg.mapper.PowerAccountMapper.selectPageInfo',
            paramMap: JSON.stringify({contractId: contractId, userId: session.userInfo.id})
        },
        dataType: 'json',
        success: function (data) {
            setNum(data);
        },
        error: function () {
            return;
        }
    });

}

function purchasePriceChange(newVale) {
    if ($(".purchaseContractId").val() == "" || $(".purchaseContractId").val() == undefined) {
        BUI.Message.Alert('请选择合约！', function () {
        }, 'warning');
        return;
    }
    $.ajax({
        type: 'post',
        url: webRoot + "/base/baseAction.do",
        cache: false,
        data: {
            sqlKey: 'com.mg.mapper.UserMapper.selectAllUser',
            paramMap: JSON.stringify({id: session.userInfo.id})
        },
        dataType: 'json',
        success: function (data) {
            if (data[0]) {
                var quantity1 = (data[0].balance - data[0].frozeMoney) / newVale
                if (quantity1) {
                    quantity = parseInt(quantity1);
                } else {
                    quantity = 0;
                }
            } else {
                quantity = 0;
            }
            $(".quantity").val(quantity);
        },
        error: function () {
            return;
        }
    });

}

function tabMenuClick(tabId) {
    curTabId = tabId;
    curDialogTabId = tabId;
    var obj = {}
    obj.start = 0; //返回第一页
    if (tabId == 0) {
        obj.type = 0
        obj.state = "交易中"
        obj.userId = session.userInfo.id
        store.load(obj);
    }
    if (tabId == 1) {
        obj.type = 1
        obj.state = "交易中"
        obj.userId = session.userInfo.id
        store.load(obj);
    } else if (tabId == 11) {
        $("#saleInfoForm").hide();
        $("#purchaseInfoForm").show();
    } else if (tabId == 12) {
        $("#purchaseInfoForm").hide();
        $("#saleInfoForm").show();
    }

}

function contHandle() {

}

function initForm() {
    saleInfoForm = Bui.formRender("saleInfoForm");
    buyForm = Bui.formRender("buyForm");
    purchaseInfoForm = Bui.formRender("purchaseInfoForm");
    purchaseSaleRecordEditForm = Bui.formRender("purchaseSaleRecordEditForm");
    dialog = Bui.overlay({
        id: 'dialog',
        title: "转让/收购",
        width: 500,
        height: 350,
        contentId: 'content',
        success: function () {
            var formVal;
            if ($("#saleInfoForm").is(':hidden')) {
                if (!purchaseInfoForm.isValid()) {
                    return;
                }
                formVal = purchaseInfoForm.serializeToObject();
                formVal.type = "P";
                if (formVal.totalNum > quantity) {
                    BUI.Message.Alert('金额不足，请充值！', function () {
                    }, 'warning');
                }

            } else {
                if (!saleInfoForm.isValid()) {
                    return;
                }
                formVal = saleInfoForm.serializeToObject();
                formVal.type = "S";
                if (formVal.totalNum > num) {
                    BUI.Message.Alert('出售算力不能大于拥有的算力！', function () {
                    }, 'warning');
                }
            }
            formVal.remainderNum = formVal.totalNum
            formVal.state = "交易中"
            formVal.userId = session.userInfo.id;
            formAction(formVal, urlParams.insertAction, dialog);
        }
    });
    purchaseSaleRecordDialog = Bui.overlay({
        id: 'purchaseSaleRecordEditFormDialog',
        title: "购买合约",
        width: 500,
        height: 350,
        contentId: 'purchaseSaleRecordEditFormDialogContent',
        success: function () {
            var formVal;
            if (!purchaseSaleRecordEditForm.isValid()) {
                return;
            }
            var num = $(".computingPowerNum").val()
            formVal = {
                num: num,
                id: $(".hiddenId").val()
            }
            formAction(formVal, urlParams.buyAction, purchaseSaleRecordDialog);
        }
    });
    contractBookDialog = Bui.overlay({
        id: 'contractBookId',
        title: "合约书",
        width: '100%',
        closeable: false,
        height: 500,
        footerContent: '<div class="bui-stdmod-footer"></div>',
        contentId: 'contractBook',
        buttons: [
            {
                text: '同意',
                elCls: 'button button-primary',
                handler: function () {
                    buyContract();
                }
            }, {
                text: '不同意',
                elCls: 'button',
                handler: function () {
                    this.close();
                }
            }
        ]
    });

}

function buyContract() {
    var
        formVal = {
            num: $(".buynum").val(),
            contractId: selectContract.id
        }
    formAction(formVal, urlParams.buyContract, contractBookDialog);

}

function formAction(formVal, actionUrl, dia) {
    CommonClass.AjaxAction(actionUrl, formVal, function (data) {
        if (data.success) {
            Message.show(data.msg, "success", 2000);
            if (dia = contractBookDialog) {
                window.location.reload();
            }
            dia.close();
        } else {
            if (data.msg) {
                Message.show(data.msg, "error", 2000);
            } else {
                Message.show("系统异常", "error", 2000);
            }

        }
    });
}